package com.pospi.xstore.ui.login_ui;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.xstore.App;
import com.pospi.xstore.R;
import com.pospi.xstore.adapter.StoreSelectionAdapter;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dto.GiveBeen;
import com.pospi.xstore.dto.ProGoodsBeen;
import com.pospi.xstore.dto.Promotionbeen;
import com.pospi.xstore.dto.ReduceProBeen;
import com.pospi.xstore.dto.ReturnDto;
import com.pospi.xstore.dto.SingleProBeen;
import com.pospi.xstore.dto.StoreMsgDto;
import com.pospi.xstore.greendao.GiveBeenDao;
import com.pospi.xstore.greendao.ProGoodsBeenDao;
import com.pospi.xstore.greendao.PromotionbeenDao;
import com.pospi.xstore.greendao.ReduceProBeenDao;
import com.pospi.xstore.greendao.SingleProBeenDao;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.MainActivity;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class SelectStoreActivity extends BaseActivity {

    @Bind(R.id.lv_store)
    ListView lvStore;

    private List<StoreMsgDto> msgDtos = new ArrayList<>();
    private StoreSelectionAdapter adapter;
    private GoodsDao goodsDao;

    private String shopId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_select_store);
        ButterKnife.bind(this);

        setTitle("店铺选择");
        setBackVisible(false);
//        saveShopMsg(getIntent().getStringExtra("value"));
        downLoadStoreMsg();

        lvStore.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                StoreMsgDto msgDto = msgDtos.get(position);
                SPHelper.getInstance().putString(Constant.STORE_ID, msgDto.getId());
                SPHelper.getInstance().putString(Constant.STORE_NAME, msgDto.getName());
//                SharedPreferences.Editor editor = getSharedPreferences("StoreMessage", MODE_PRIVATE).edit();
//                editor.putString("Id", msgDto.getId());
//                editor.putString("Name", msgDto.getName());
//                editor.putString("Address", msgDto.getAddress());
//                editor.putString("Contacts", msgDto.getContacts());
//                editor.putString("Phone", msgDto.getPhone());
//                editor.apply();
                startActivity(MainActivity.class);
//                down();
                finish();
            }
        });

    }
//    //下载促销
//    private void down() {
//        RequestParams params = new RequestParams();
//        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
//        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
//        params.put("model", "activity.api");
//        params.put("fun", "getactivity");
//        params.put("storeid", SPHelper.getInstance().getString(Constant.STORE_ID));
//        Log.i("goods", params.toString());
//        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(int i, Header[] headers, final byte[] bytes) {
//                Log.i("promotion", new String(bytes));
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        savePro(new String(bytes));
//                    }
//                }).start();
//
//
//            }
//
//            @Override
//            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
//            }
//        });
//
//    }


//    //存储活动
//    private void savePro(String s) {
//        PromotionbeenDao promotionbeenDao= App.getInstance().getDaoSession().getPromotionbeenDao();
//        SingleProBeenDao singleProBeenDao= App.getInstance().getDaoSession().getSingleProBeenDao();
//        ProGoodsBeenDao proGoodsBeenDao= App.getInstance().getDaoSession().getProGoodsBeenDao();
//        GiveBeenDao giveBeenDao= App.getInstance().getDaoSession().getGiveBeenDao();
//        ReduceProBeenDao reduceProBeenDao= App.getInstance().getDaoSession().getReduceProBeenDao();
//        proGoodsBeenDao.deleteAll();
//        reduceProBeenDao.deleteAll();
//        proGoodsBeenDao.deleteAll();
//        giveBeenDao.deleteAll();
//        singleProBeenDao.deleteAll();
//        try {
//            JSONObject object = new JSONObject(s);
//            JSONObject result = object.getJSONObject("result");
//            List<Promotionbeen> promotionbeens = new Gson().fromJson(result.getJSONArray("head").toString(), new TypeToken<List<Promotionbeen>>() {
//            }.getType());
//            List<ReduceProBeen> reduceProBeens = new Gson().fromJson(result.getJSONArray("discou").toString(), new TypeToken<List<ReduceProBeen>>() {
//            }.getType());
//            List<ProGoodsBeen> proGoodsBeens = new Gson().fromJson(result.getJSONArray("goods").toString(), new TypeToken<List<ProGoodsBeen>>() {
//            }.getType());
//            List<GiveBeen> giveBeens = new Gson().fromJson(result.getJSONArray("nplusn").toString(), new TypeToken<List<GiveBeen>>() {
//            }.getType());
//            List<SingleProBeen> singleProBeens = new Gson().fromJson(result.getJSONArray("mgooddiscou").toString(), new TypeToken<List<SingleProBeen>>() {
//            }.getType());
//            for (Promotionbeen promotionbeen : promotionbeens) {
//                promotionbeenDao.insert(promotionbeen);
//            }
//            for (ReduceProBeen reduceProBeen : reduceProBeens) {
//                reduceProBeenDao.insert(reduceProBeen);
//            }
//            for (ProGoodsBeen proGoodsBeen : proGoodsBeens) {
//                proGoodsBeenDao.insert(proGoodsBeen);
//            }
//            for (GiveBeen giveBeen : giveBeens) {
//                giveBeenDao.insert(giveBeen);
//            }
//            for (SingleProBeen been : singleProBeens) {
//                singleProBeenDao.insert(been);
//            }
//
//            Log.i("data", "活动存储完成" +promotionbeens.size()+"-----"+reduceProBeens.size()+"-----"+proGoodsBeens.size()+"-----"+giveBeens.size()+"-----"+singleProBeens.size());
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//    }


    public void downLoadStoreMsg() {
        RequestParams params = new RequestParams();
        params.put("model", "base.mbase");
        params.put("fun", "find");
        params.put("table", "base_market");
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("page", "");
        params.put("limit", "");

        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int position, Header[] headers, byte[] bytes) {
                Log.i("responseBody", new String(bytes));
                ReturnDto returnDto = new ReturnDto();
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    returnDto.setResult(Integer.parseInt(object.getString("flag")));
                    returnDto.setMessage(object.getString("errMsg"));
                    JSONArray array = object.getJSONArray("result");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object1 = (JSONObject) array.opt(i);
                        StoreMsgDto msgDto = new StoreMsgDto();
                        msgDto.setId(object1.getString("id"));
                        msgDto.setName(object1.getString("name"));
                        msgDtos.add(msgDto);
                    }
                    adapter = new StoreSelectionAdapter(msgDtos, getApplicationContext());
                    lvStore.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }
    /*
店铺信息
 */
    private void saveShopMsg(String value) {
        Log.i("msg", value);
//        List<StoreMsgDto> msgDtos = new ArrayList<>();
        try {
            JSONArray array = new JSONArray(value);
            for (int j = 0; j < array.length(); j++) {
                JSONObject object1 = (JSONObject) array.opt(j);
                StoreMsgDto msgDto = new StoreMsgDto();
                msgDto.setId(object1.getString("id"));
                msgDto.setName(object1.getString("sh_name"));
                msgDto.setAddress(object1.getString("address"));
                msgDto.setPhone(object1.getString("tel"));
//                msgDto.setContacts(object1.getString("Contacts"));
//                msgDto.setContacts(object1.getString("Contacts"));
//                msgDto.setDiscount((float) object1.getDouble("Discount"));
                msgDtos.add(msgDto);
            }


            //解析value得到店铺的信息
            adapter = new StoreSelectionAdapter(msgDtos, getApplicationContext());
            lvStore.setAdapter(adapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
